<template>
  <div class="report-container table_zoom"
       style="width:100%;">
    <Row type='flex'
         justify="space-between"
         class="coinrevenue-list-edit">
      <Row type='flex'
           align='middle'>
        <Col>
        <span class="concrete-data">时间：</span>
        <datePickerYmd @on-change="searchgroupbuying"
                       :selectDateType.sync='selectDateType'
                       :dataType="dataType"
                       :dateOption="dateOption"
                       v-model="timeDate"
                       style="display:inline-block"></datePickerYmd>
        </Col>
        <Row type='flex'
             align='middle'
             class="export-btn">
          <Col><span>门店名称：</span></Col>
          <Col>
          <!-- <Select v-model="searchObj.shopId"
                  multiple
                  filterable
                  @on-change="selectshop"
                  class="select-shop-item"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  style="width:210px">
            <Option v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select> -->
          <!-- <vueTreeselectShop :shopList.sync="searchObj.shopId"
                             @id-change="searchgroupbuying"
                             permissionCode="moms:report:otherrevenue"
                             v-model="testValue"></vueTreeselectShop> -->
          <vueTreeselectChoice :multiple="true"
                               ref="vueTreeselectChoice"
                               @input="handleShop"
                               @on-api-finish="apiFinish"
                               permissionCode="moms:report:otherrevenue"
                               v-model="ShopValue"></vueTreeselectChoice>
          </Col>
          <Col>
          <Button type="primary"
                  class="coinrevenue-btn export-btn"
                  @click="searchgroupbuying">查询</Button>
          </Col>
        </Row>
      </Row>
      <Col>
      <Button class="coinrevenue-btn"
              @click="exportData"
              v-if="hasPermission('moms:report:otherrevenueexport')">导出</Button>
      </Col>
    </Row>
    <Table stripe
           ref="rowSpanTable"
           :loading="isloading"
           :height="this.tableHeight"
           border
           class="table-list"
           :columns="columns"
           :data="resData">
      <template slot-scope="{ row }"
                slot="payableFee">
        <span>{{formatAmount(row.payableFee)}}</span>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:otherrevenue"
                 v-if="hasPermission('moms:report:otherrevenueexport')"></down-center>
  </div>
</template>
<script>
import '../../report.less'
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { groupbuyingList } from '@/api/report/finance'
// import { blobToXls } from '@/libs/blobToXls'
import { formatAmount } from '@/libs/tools'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
import DownCenter from '@/view/components/down-center/index.vue'
export default {
  name: 'report_finance_otherrevenue_group_detail',
  components: { vueTreeselectChoice, datePickerYmd, DownCenter },
  data () {
    return {
      dataChoose: '',
      shopName: null,
      ShopValue: [],
      options: [],
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      timeDate: JSON.parse(localStorage.getItem('group')) ? JSON.parse(localStorage.getItem('group')).timeDate : JSON.parse(localStorage.getItem('groupd')).timeDate,
      selectDateType: JSON.parse(localStorage.getItem('group')) ? JSON.parse(localStorage.getItem('group')).selectDateType : JSON.parse(localStorage.getItem('groupd')).selectDateType,
      testValue: JSON.parse(localStorage.getItem('group')) ? JSON.parse(localStorage.getItem('group')).id : JSON.parse(localStorage.getItem('groupd')).id,
      tableHeight: 0,
      isloading: false,
      formatAmount: formatAmount,
      title: '今日另收表-团购明细',
      value: null,
      columns: [
        { title: '门店', key: 'shopName', align: 'center', width: 200 },
        { title: '收入时间', key: 'systemTime', align: 'center' },
        { title: '收款时间', key: 'createTime', align: 'center' },
        { title: '商户名称', key: 'payPlatform', align: 'center' },
        { title: '收款金额(元)', align: 'center', slot: 'payableFee' },
        { title: '支付方式', key: 'payCode', align: 'center' },
        { title: '操作人', key: 'cashierName', align: 'center' },
        { title: '备注', key: 'serviceRemark', align: 'center' }
      ],
      shopList: [],
      total: 0,
      searchObj: {
        shopId: [],
        offset: 1,
        limit: 10
      },
      resData: []
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      return this.timeDate[1]
    }
  },
  watch: {
    '$route' (newRouter) {
    }
  },
  mounted () {
    // this.getShopList()
  },
  updated () {
    this.$nextTick(() => {
      // rowSpanTable(this.$refs.rowSpanTable, 'shopName', false)
    })
  },
  destroyed () {
    localStorage.removeItem('group')
  },
  methods: {
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      localStorage.setItem('groupd', JSON.stringify({ id: this.searchObj.shopId, type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      this.searchgroupbuying()
    },
    apiFinish () {
      this.ShopValue = JSON.parse(localStorage.getItem('group')) ? JSON.parse(localStorage.getItem('group')).id : JSON.parse(localStorage.getItem('groupd')).id
    },
    exportData () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$refs.downCenterRef.addTask({
          merchantId: this.$store.state.user.merchantId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate,
          dateType: { year: 2, month: 1, date: 0 }[this.selectDateType],
          taskModule: 'todayExtraIncomeGroupDetail'
        })
        // groupbuyingExport({
        //   merchantId: this.$store.state.user.merchantId,
        //   shopIds: this.searchObj.shopId,
        //   startDate: this.startDate,
        //   endDate: this.endDate
        // }).then(res => {
        //   if (res.status === 200) {
        //     if (this.selectDateType === 'month') {
        //       blobToXls(res.data, `今日另收表-团购明细表(${this.startDate.substring(0, 7)})`)
        //     } else if (this.selectDateType === 'date') {
        //       blobToXls(res.data, `今日另收表-团购明细表(${this.startDate.substring(0, 10)})`)
        //     } else {
        //       blobToXls(res.data, `今日另收表-团购明细表(${this.startDate.substring(0, 4)})`)
        //     }
        //   } else {
        //     this.$Message.error(`${res.data.error}`)
        //   }
        // })
      }
    },
    getList () {
      this.isloading = true
      this.tableHeight = 0
      this.resData = []
      groupbuyingList({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit
      }).then(res => {
        this.isloading = false
        if (res.data.status === 200) {
          this.total = res.data.totalCount
          if (res.data.data && res.data.data.length >= 14) {
            this.tableHeight = 520
          }
          this.resData = res.data.data ? res.data.data : []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    searchgroupbuying () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getList()
      }
    },
    filtersResData (data) {
      data.map((ele, idx, arr) => {
        arr[idx].payableFee = formatAmount(arr[idx].payableFee)
      })
      return data
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      this.getList()
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      this.getList()
    }
  }
}
</script>
